'use strict';

const Service = require('egg').Service;
const Mock = require('mockjs');

class AuditService extends Service {
    async getList() {
        const {
            ctx,
            app
        } = this;
        // const {list} = Mock.mock({
        //     "list|10":[
        //         {
        //             plot:"@ctitle(4,8)",
        //             title:"@ctitle(6,15)",
        //             "area|30-100":30,
        //             "price|30-100":30, 
        //             sort:1,
        //             "state|1":['待审核','审核通过','审核不通过']//状态
        //         }
        //     ]
        // });
        // list.forEach((item)=>{
        //     app.mysql.insert('audits',{
        //         ...item
        //     })
        // })
        // return '123'
        const {
            pageSize,
            pageIndex,
            state,
            area,
            title
        } = ctx.query;
        let sql = `select * from audits where 1=1 `;
        let sqlCount = `select count(id) as total from audits where 1=1 `;
        if(title) {
            sql += `and title like '%${title}%' `
            sqlCount += `and title like '%${title}%' `
        }
        // 状态
        if (state) {
            sql += `and state = '${state}' `
            sqlCount += `and state = '${state}' `
        }
        // 区域
        if (area) {
            sql += `and area like '%${area}%' `
            sqlCount += `and area like '%${area}%' `
        }
        //分页
        if (pageSize && pageIndex) {
            sql += `limit ${(pageIndex-1)*pageSize},${pageSize} `
        }
        let res = await app.mysql.query(sql);
        let [{
            total
        }] = await app.mysql.query(sqlCount);
        res.forEach((item, index) => {
            // 序号
            item.number = (pageIndex - 1) * 5 + index + 1;
        })

        return {
            data: res,
            total: total
        }
    }
    // 删除审核
    async delAudit() {
        const {
            ctx,
            app
        } = this;
        const {
            id
        } = ctx.request.body;
        let res = await app.mysql.delete('audits', {
            id
        });
        return res
    }
    // 编辑审核
    async editAudit() {
        const {
            ctx,
            app
        } = this;
        const {
            id,
            plot,
            title,
            acreage,
            price,
            sort,
            state,
            area
        } = ctx.request.body;
        let res = await app.mysql.update('audits', {
            id,
            plot,
            title,
            acreage,
            price,
            sort,
            state,
            area
        });
        return res
    }
}

module.exports = AuditService;